package com.zifeng.study.springbootshirojwtdemo.shiro;

import com.zifeng.study.springbootshirojwtdemo.bean.Permission;
import com.zifeng.study.springbootshirojwtdemo.bean.Role;
import com.zifeng.study.springbootshirojwtdemo.mapper.PermissionMapper;
import com.zifeng.study.springbootshirojwtdemo.mapper.RoleMapper;
import com.zifeng.study.springbootshirojwtdemo.mapper.UserMapper;
import com.zifeng.study.springbootshirojwtdemo.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: 吴梓锋
 * @date: 2022/01/14 16:02:51
 * @version: 1.0.0
 * @description: 自定义Realm，主要用于token校验及权限校验
 */
@Component
@Slf4j
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;

    /**
     * 必须重写此方法，不然会报不支持该token的错误
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 权限校验逻辑
     *
     * @param principalCollection token
     * @return 权限校验信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取userId，这里的principalCollection里面存放的是我们的Token
        int userId = Integer.parseInt(JwtUtil.getAudience(principalCollection.toString()));

        // 校验信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 获得该用户角色id
        int roleId = userMapper.getUserByUserId(userId).getRoleId();

        // 获得该用户角色然后将角色加进校验信息中
        Role role = roleMapper.getRoleById(roleId);
        Set<String> roleSet = new HashSet<>();
        roleSet.add(role.getRoleName());
        info.setRoles(roleSet);

        // 获取用户权限列表，然后将对应权限加进校验信息中
        List<Permission> userPermissions = permissionMapper.getPermissionsByUserId(userId);
        Set<String> permissionSet = new HashSet<>();
        userPermissions.forEach(bean -> permissionSet.add(bean.getPermissionName()));
        info.setStringPermissions(permissionSet);

        return info;
    }

    /**
     * token校验逻辑
     *
     * @param authenticationToken token类
     * @return 校验结果
     * @throws AuthenticationException 校验失败异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // Token校验逻辑
        String token = (String) authenticationToken.getCredentials();
        // 获取用户id
        String userId = JwtUtil.getAudience(token);
        // 校验Token，如果校验错误内部会抛出异常
        JwtUtil.verifyToken(token, userId);
        return new SimpleAuthenticationInfo(token, token, "CustomRealm");
    }

}
